#!/usr/bin/env python3.6

import requests
from io import BytesIO
import bencode3
import hashlib
import base64

from url_heade import read_Headers

head=read_Headers()
# print(head)

def get_magnetic_link(url):
    torrent_url = url
    r = requests.get(torrent_url,headers=head)
    tmp_file = BytesIO(r.content)
    torrent = tmp_file.read()
    #计算meta数据
    metadata = bencode3.bdecode(torrent)
    hashcontents = bencode3.bencode(metadata['info'])

    digest = hashlib.sha1(hashcontents).digest()

    b32hash = base64.b32encode(digest,)


    b32hash=str(b32hash,encoding='utf-8')


    #打印
    # print ('magnet:?xt=urn:btih:%s' % b32hash)
    return 'magnet:?xt=urn:btih:%s' % b32hash

if __name__ == '__main__':
    get_magnetic_link("http://www.btbtt.net/attach-download-fid-951-aid-4681954.htm")